package io;

import java.io.*;

public class TestClose {

    public static void main(String[] args) {

    }

    // 一个简单的复制文件方法。
    public static void copy(String src, String dst) {//d:\\a.txt    E:\\a.txt
        InputStream in = null;
        OutputStream out = null;
        try {//包裹可能出现异常的代码
            in = new FileInputStream(src);
            out = new FileOutputStream(dst);
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (IOException e) {//处理异常~~~~
            e.printStackTrace();
        } finally {//关闭资源
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //jdk7,简化，自动关闭流
    public static void copy2(String src, String dst) {
        try (InputStream in = new FileInputStream(src);
             OutputStream out = new FileOutputStream(dst)) {//把要关闭资源放到try()中
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //jdk9,再次简化
    public static void copy3(String src, String dst) throws FileNotFoundException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
        try (in;out) {
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
